<template>
  <div class="admin-forum-manage">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <div class="search-container">
        <div class="search-row">
          <div class="search-item">
            <label>标题：</label>
            <el-input 
              v-model="searchParams.title" 
              placeholder="请输入标题关键词" 
              clearable
              style="width: 250px;">
            </el-input>
          </div>
          
          <div class="search-item">
            <label>关键词：</label>
            <el-input 
              v-model="searchParams.keywords" 
              placeholder="请输入关键词" 
              clearable
              style="width: 250px;">
            </el-input>
          </div>
          
          <div class="search-item">
            <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            <el-button icon="el-icon-refresh-left" @click="handleReset">重置</el-button>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table 
        :data="tableData" 
        style="width: 100%"
        :header-cell-style="{background: '#f5f7fa', color: '#606266'}">
        
        <el-table-column prop="id" label="ID" min-width="80"></el-table-column>
        
        <el-table-column label="图片" min-width="150">
          <template slot-scope="scope">
            <div class="images-stack" v-if="scope.row.images">
              <div class="stacked-images">
                <img 
                  v-for="(img, index) in getImageArray(scope.row.images).slice(0, 3)" 
                  :key="index"
                  :src="img"
                  :style="{zIndex: 3 - index, left: (index * 15) + 'px'}"
                  @click="handlePreviewImages(getImageArray(scope.row.images), index)">
                <span class="image-count" v-if="getImageArray(scope.row.images).length > 1">
                  {{ getImageArray(scope.row.images).length }}张
                </span>
              </div>
            </div>
            <span v-else class="no-image">无图片</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="title" label="标题" min-width="200"></el-table-column>
        
        <el-table-column prop="description" label="描述" min-width="250" show-overflow-tooltip></el-table-column>
        
        <el-table-column label="关键词" min-width="150">
          <template slot-scope="scope">
            <el-tag 
              v-for="(keyword, index) in getKeywordArray(scope.row.keywords)" 
              :key="index"
              size="mini"
              type="info"
              style="margin-right: 5px; margin-bottom: 3px;">
              {{ keyword }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="username" label="发布人" min-width="120"></el-table-column>
        
        <el-table-column label="统计" min-width="120">
          <template slot-scope="scope">
            <div>
              <el-tag size="mini" type="danger">👍 {{ scope.row.likeCount }}</el-tag>
              <el-tag size="mini" type="warning" style="margin-left: 5px;">💬 {{ scope.row.commentCount }}</el-tag>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="createTime" label="发布时间" min-width="180">
          <template slot-scope="scope">
            {{ formatTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" min-width="200" fixed="right">
          <template slot-scope="scope">
            <el-button 
              type="primary" 
              size="mini" 
              icon="el-icon-view"
              @click="handleViewDetail(scope.row)">
              详情
            </el-button>
            <el-button 
              type="success" 
              size="mini" 
              icon="el-icon-edit"
              @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button 
              type="danger" 
              size="mini" 
              icon="el-icon-delete"
              @click="handleDelete(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange">
        </el-pagination>
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog 
      title="帖子详情" 
      :visible.sync="detailDialogVisible" 
      width="900px"
      top="5vh">
      <div class="post-detail" v-if="currentPost.id">
        <div class="detail-section">
          <h3>{{ currentPost.title }}</h3>
          <div class="post-meta">
            <el-tag size="small" type="info">发布人：{{ currentPost.username }}</el-tag>
            <el-tag size="small" type="warning" style="margin-left: 10px;">点赞：{{ currentPost.likeCount }}</el-tag>
            <el-tag size="small" type="success" style="margin-left: 10px;">评论：{{ currentPost.commentCount }}</el-tag>
            <span style="margin-left: 10px; color: #909399;">{{ formatTime(currentPost.createTime) }}</span>
          </div>
        </div>

        <div class="detail-section" v-if="currentPost.keywords">
          <label>关键词：</label>
          <el-tag 
            v-for="(keyword, index) in getKeywordArray(currentPost.keywords)" 
            :key="index"
            size="small"
            type="info"
            style="margin-right: 8px;">
            {{ keyword }}
          </el-tag>
        </div>

        <div class="detail-section" v-if="currentPost.description">
          <label>描述：</label>
          <p class="description-text">{{ currentPost.description }}</p>
        </div>

        <div class="detail-section" v-if="currentPost.images">
          <label>图片：</label>
          <div class="detail-images">
            <el-image
              v-for="(image, index) in getImageArray(currentPost.images)"
              :key="index"
              :src="image"
              :preview-src-list="getImageArray(currentPost.images)"
              fit="cover"
              class="detail-image">
            </el-image>
          </div>
        </div>

        <div class="detail-section">
          <label>正文：</label>
          <div class="content-text">
            <pre>{{ currentPost.content }}</pre>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog 
      title="编辑帖子" 
      :visible.sync="editDialogVisible" 
      width="800px"
      :close-on-click-modal="false">
      <el-form :model="editForm" :rules="editRules" ref="editForm" label-width="100px">
        <el-form-item label="帖子图片" prop="images">
          <div class="upload-container">
            <div class="image-list">
              <div 
                v-for="(img, index) in editForm.imageList" 
                :key="index" 
                class="image-item">
                <img :src="img" alt="帖子图片">
                <div class="image-overlay">
                  <i class="el-icon-zoom-in" @click="handlePreviewImage(index)"></i>
                  <i class="el-icon-delete" @click="handleRemoveImage(index)"></i>
                </div>
              </div>
              
              <el-upload
                v-if="editForm.imageList.length < 5"
                class="image-uploader"
                action=""
                :show-file-list="false"
                :before-upload="handleBeforeUpload"
                :http-request="handleUploadImage">
                <i class="el-icon-plus upload-icon"></i>
                <div class="upload-text">上传图片</div>
              </el-upload>
            </div>
            <div class="upload-tip">最多可上传5张图片，支持jpg、png格式，单张图片不超过2MB</div>
          </div>
        </el-form-item>
        
        <el-form-item label="标题" prop="title">
          <el-input v-model="editForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        
        <el-form-item label="关键词" prop="keywords">
          <el-input v-model="editForm.keywords" placeholder="请输入关键词，多个关键词用逗号分隔"></el-input>
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="editForm.description" 
            type="textarea"
            :rows="3"
            placeholder="请输入描述">
          </el-input>
        </el-form-item>
        
        <el-form-item label="正文" prop="content">
          <el-input 
            v-model="editForm.content" 
            type="textarea"
            :rows="6"
            placeholder="请输入正文内容">
          </el-input>
        </el-form-item>
      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitEdit" :loading="submitLoading">确定</el-button>
      </div>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog 
      title="图片预览" 
      :visible.sync="imagePreviewVisible" 
      width="800px"
      @close="handleClosePreview">
      <div class="image-preview-container">
        <el-image
          :src="currentPreviewImage"
          fit="contain"
          style="width: 100%; max-height: 600px;">
        </el-image>
        <div class="preview-controls">
          <el-button 
            icon="el-icon-arrow-left" 
            :disabled="currentImageIndex === 0"
            @click="handlePrevImage">
            上一张
          </el-button>
          <span class="image-indicator">{{ currentImageIndex + 1 }} / {{ previewImages.length }}</span>
          <el-button 
            icon="el-icon-arrow-right" 
            :disabled="currentImageIndex === previewImages.length - 1"
            @click="handleNextImage">
            下一张
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAdminPostList, adminDeletePost, getPostById, adminUpdatePost } from '@/api/forum'
import { uploadFile } from '@/api/file'

export default {
  name: 'AdminForumManage',
  data() {
    return {
      searchParams: {
        title: '',
        keywords: ''
      },
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      detailDialogVisible: false,
      currentPost: {},
      imagePreviewVisible: false,
      previewImages: [],
      currentImageIndex: 0,
      currentPreviewImage: '',
      
      // 编辑相关
      editDialogVisible: false,
      submitLoading: false,
      editForm: {
        id: null,
        title: '',
        keywords: '',
        description: '',
        content: '',
        images: '',
        imageList: []
      },
      editRules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入正文内容', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.loadData()
  },
  methods: {
    // 加载数据
    async loadData() {
      try {
        const params = {
          ...this.searchParams,
          page: this.currentPage,
          size: this.pageSize
        }
        
        const response = await getAdminPostList(params)
        if (response.data.code === 200) {
          const data = response.data.data
          this.tableData = data.list
          this.total = data.total
        }
      } catch (error) {
        console.error('加载数据失败', error)
        this.$notify.error({
          title: '错误',
          message: '加载数据失败'
        })
      }
    },

    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.loadData()
    },

    // 重置
    handleReset() {
      this.searchParams = {
        title: '',
        keywords: ''
      }
      this.currentPage = 1
      this.loadData()
    },

    // 分页大小改变
    handleSizeChange(size) {
      this.pageSize = size
      this.currentPage = 1
      this.loadData()
    },

    // 页码改变
    handlePageChange(page) {
      this.currentPage = page
      this.loadData()
    },

    // 查看详情
    async handleViewDetail(row) {
      try {
        const response = await getPostById(row.id)
        if (response.data.code === 200) {
          this.currentPost = response.data.data
          this.detailDialogVisible = true
        }
      } catch (error) {
        console.error('加载详情失败', error)
        this.$notify.error({
          title: '错误',
          message: '加载详情失败'
        })
      }
    },

    // 删除
    handleDelete(id) {
      this.$confirm('确定要删除这篇帖子吗？删除后无法恢复', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await adminDeletePost(id)
          if (response.data.code === 200) {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            this.loadData()
          } else {
            this.$notify.error({
              title: '错误',
              message: response.data.message || '删除失败'
            })
          }
        } catch (error) {
          console.error('删除失败', error)
          this.$notify.error({
            title: '错误',
            message: '删除失败'
          })
        }
      }).catch(() => {})
    },

    // 获取图片数组
    getImageArray(images) {
      if (!images) return []
      return images.split(',').filter(img => img.trim())
    },

    // 获取关键词数组
    getKeywordArray(keywords) {
      if (!keywords) return []
      return keywords.split(',').filter(kw => kw.trim())
    },

    // 预览图片
    handlePreviewImages(images, index) {
      this.previewImages = images
      this.currentImageIndex = index
      this.currentPreviewImage = images[index]
      this.imagePreviewVisible = true
    },

    // 上一张图片
    handlePrevImage() {
      if (this.currentImageIndex > 0) {
        this.currentImageIndex--
        this.currentPreviewImage = this.previewImages[this.currentImageIndex]
      }
    },

    // 下一张图片
    handleNextImage() {
      if (this.currentImageIndex < this.previewImages.length - 1) {
        this.currentImageIndex++
        this.currentPreviewImage = this.previewImages[this.currentImageIndex]
      }
    },

    // 关闭预览
    handleClosePreview() {
      this.previewImages = []
      this.currentImageIndex = 0
      this.currentPreviewImage = ''
    },

    // 编辑帖子
    async handleEdit(row) {
      try {
        const response = await getPostById(row.id)
        if (response.data.code === 200) {
          const postData = response.data.data
          this.editForm = {
            id: postData.id,
            title: postData.title,
            keywords: postData.keywords || '',
            description: postData.description || '',
            content: postData.content,
            images: postData.images || '',
            imageList: this.getImageArray(postData.images)
          }
          this.editDialogVisible = true
        }
      } catch (error) {
        console.error('加载帖子详情失败', error)
        this.$notify.error({
          title: '错误',
          message: '加载帖子详情失败'
        })
      }
    },

    // 提交编辑
    handleSubmitEdit() {
      this.$refs.editForm.validate(async (valid) => {
        if (valid) {
          this.submitLoading = true
          try {
            const submitData = {
              ...this.editForm,
              images: this.editForm.imageList.join(',')
            }
            delete submitData.imageList
            
            const response = await adminUpdatePost(submitData)
            if (response.data.code === 200) {
              this.$notify.success({
                title: '成功',
                message: '更新成功'
              })
              this.editDialogVisible = false
              this.loadData()
            } else {
              this.$notify.error({
                title: '错误',
                message: response.data.message || '更新失败'
              })
            }
          } catch (error) {
            console.error('更新失败', error)
            this.$notify.error({
              title: '错误',
              message: '更新失败'
            })
          } finally {
            this.submitLoading = false
          }
        }
      })
    },

    // 上传前校验
    handleBeforeUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2
      
      if (!isImage) {
        this.$notify.error({
          title: '错误',
          message: '只能上传图片文件'
        })
        return false
      }
      
      if (!isLt2M) {
        this.$notify.error({
          title: '错误',
          message: '图片大小不能超过2MB'
        })
        return false
      }
      
      return true
    },

    // 上传图片
    async handleUploadImage(params) {
      try {
        const response = await uploadFile(params.file)
        if (response.data.success) {
          const imageUrl = response.data.data
          this.editForm.imageList.push(imageUrl)
          this.$notify.success({
            title: '成功',
            message: '图片上传成功'
          })
        } else {
          this.$notify.error({
            title: '错误',
            message: response.data.message || '图片上传失败'
          })
        }
      } catch (error) {
        this.$notify.error({
          title: '错误',
          message: '图片上传失败'
        })
      }
    },

    // 删除图片
    handleRemoveImage(index) {
      this.editForm.imageList.splice(index, 1)
    },

    // 预览图片（表单中）
    handlePreviewImage(index) {
      this.previewImages = [...this.editForm.imageList]
      this.currentImageIndex = index
      this.currentPreviewImage = this.editForm.imageList[index]
      this.imagePreviewVisible = true
    },

    // 格式化时间
    formatTime(time) {
      if (!time) return ''
      const date = new Date(time)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
  }
}
</script>

<style scoped>
.admin-forum-manage {
  padding: 0;
}

.search-card {
  margin-bottom: 20px;
}

.search-container {
  padding: 10px 0;
}

.search-row {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 20px;
}

.search-item {
  display: flex;
  align-items: center;
}

.search-item label {
  white-space: nowrap;
  margin-right: 10px;
  font-weight: 500;
  color: #606266;
}

.table-card {
  background: white;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 层叠图片样式 */
.images-stack {
  position: relative;
  height: 60px;
}

.stacked-images {
  position: relative;
  height: 60px;
  width: 120px;
}

.stacked-images img {
  position: absolute;
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  border: 2px solid white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  cursor: pointer;
  transition: all 0.3s;
}

.stacked-images img:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.25);
}

.image-count {
  position: absolute;
  right: 10px;
  bottom: 5px;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;
  z-index: 10;
}

.no-image {
  color: #909399;
  font-size: 14px;
}

/* 详情对话框样式 */
.post-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 25px;
}

.detail-section h3 {
  font-size: 22px;
  color: #303133;
  margin: 0 0 15px 0;
}

.post-meta {
  margin-bottom: 10px;
}

.detail-section label {
  display: block;
  font-weight: 600;
  color: #606266;
  margin-bottom: 10px;
  font-size: 15px;
}

.description-text {
  color: #606266;
  line-height: 1.6;
  padding: 12px;
  background: #f5f7fa;
  border-radius: 4px;
  margin: 0;
}

.detail-images {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 10px;
}

.detail-image {
  width: 100%;
  height: 150px;
  border-radius: 4px;
  cursor: pointer;
}

.content-text {
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
  line-height: 1.8;
}

.content-text pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: inherit;
  margin: 0;
  color: #303133;
}

/* 图片预览样式 */
.image-preview-container {
  text-align: center;
}

.preview-controls {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
}

.image-indicator {
  font-size: 16px;
  color: #606266;
  font-weight: 500;
}

/* 编辑对话框样式 */
.upload-container {
  width: 100%;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 10px;
}

.image-item {
  position: relative;
  width: 120px;
  height: 120px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.image-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
  opacity: 0;
  transition: opacity 0.3s;
}

.image-item:hover .image-overlay {
  opacity: 1;
}

.image-overlay i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  transition: transform 0.3s;
}

.image-overlay i:hover {
  transform: scale(1.2);
}

.image-uploader {
  width: 120px;
  height: 120px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  transition: border-color 0.3s;
}

.image-uploader:hover {
  border-color: #409eff;
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
}

.upload-text {
  margin-top: 8px;
  color: #8c939d;
  font-size: 12px;
}

.upload-tip {
  color: #999;
  font-size: 12px;
  line-height: 1.5;
}
</style>

